package com.educate.service.impl;

import com.educate.common.dto.MenuNavDto;
import com.educate.dao.UserDao;
import com.educate.util.RedisUtil;
import com.educate.dao.MenuDao;
import com.educate.pojo.Menu;
import com.educate.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yjj
 * @date 2021/11/17
 * @description: MenuServiceImpl
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private MenuDao menuDao;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户导航信息
     * @return  List<MenuNavDto>
     */
    @Override
    public List<MenuNavDto> getNavList() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        Long roleId = userDao.getRoleIdByUserName(username);
        List<Menu> menuList;
        String redisKey = "UserNav:" + roleId;
        if(redisUtil.get(redisKey) == null){
            menuList = menuDao.getMenuListByRoleId(roleId);
            redisUtil.set(redisKey, menuList);
        }else {
            menuList =(List<Menu>)redisUtil.get(redisKey);
        }
        List<Menu> menuTree = buildTree(menuList);
        return convertToDto(menuTree);
    }
    /**
     * 转换为DTO
     * @param menuTree
     * @return  List<MenuNavDto>
     */

    private List<MenuNavDto> convertToDto(List<Menu> menuTree) {
        List<MenuNavDto> menuNavList = new ArrayList<>();
        for (Menu menu : menuTree) {
            MenuNavDto menuNavDto = new MenuNavDto();
            menuNavDto.setId(menu.getId());
            menuNavDto.setPath(menu.getPath());
            menuNavDto.setIcon(menu.getIcon());
            menuNavDto.setTitle(menu.getName());
            if(menu.getChildren().size() > 0){
                menuNavDto.setChildren(convertToDto(menu.getChildren()));
            }
            menuNavList.add(menuNavDto);
        }
        return menuNavList;
    }
    /**
     * 构建菜单树
     * @param menuList
     * @return List<Menu>
     */
    private List<Menu> buildTree(List<Menu> menuList) {
        List<Menu> resultList = new ArrayList<>();
        for (Menu m1 : menuList) {
            for (Menu m2 : menuList) {
                if(m1.getId().equals(m2.getParentId())){
                    m1.getChildren().add(m2);
                }
            }
            if(m1.getParentId() == 0L){
                resultList.add(m1);
            }
        }
        return resultList;
    }
}
